package com.zeng.sim.support.protocol;

import com.zeng.sim.controller.domain.msg.MsgData;
import com.zeng.sim.util.SimConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Objects;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-12-25T15:34
 */
@Component
public class HttpMsgProtocol implements IMsgProtocol {

    private Logger logger = LoggerFactory.getLogger(HttpMsgProtocol.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 是否支持
     * @param msgProtocol
     * @return
     */
    @Override
    public boolean support(SimConstant.MsgProtocol msgProtocol) {
        return SimConstant.MsgProtocol.MSG_PROTOCOL_HTTP.equals(msgProtocol);
    }

    /**
     * 发送消息
     * @param msgData
     * @return 响应报文
     */
    @Override
    public String sendMsg(MsgData msgData) {
        logger.info("客户端发起请求，url[{}]，httpMethod[{}]", msgData.getUrl(), msgData.getHttpMethod());
        logger.info("发送请求报文[{}]", msgData.getMsgContent());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType(msgData.getMediaType()));
        httpHeaders.setAcceptCharset(Collections.singletonList(Charset.forName(msgData.getCharsetName())));

        HttpEntity<String> httpEntity = new HttpEntity<>(msgData.getMsgContent(), httpHeaders);

        ResponseEntity<String> responseEntity = restTemplate.exchange(msgData.getUrl(),
                Objects.requireNonNull(HttpMethod.resolve(msgData.getHttpMethod())), httpEntity, String.class);
        if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            throw new IllegalStateException("请求出错，状态码：" + responseEntity.getStatusCode().toString());
        }
        String respMsg = responseEntity.getBody();
        logger.info("收到响应报文[{}]", respMsg);
        return respMsg;
    }

}
